package io.gitee.xyuesheng.day07;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;

public class TestFiles {
    //visitor封装了文件处理的逻辑
    private FileVisitor<Path> visitor = new FileVisitor<Path>() {
        //访问目录之前要做的事情
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            //继续访问
            return FileVisitResult.CONTINUE;
        }

        //访问文件时所作的处理
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println(file.getFileName());

//            //file.tofile()将Path类转化成File类
//            File file1=file.toFile();
//            file1.length();

            if (file.getFileName().toString().startsWith("HomeworkBook")) {
                System.out.println("###");
                return FileVisitResult.TERMINATE;
                //CONTINUE继续打印
//                return FileVisitResult.CONTINUE;
            }
            return FileVisitResult.CONTINUE;
        }

        //
        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        //访问目录之后所作的处理
        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    };

    @Test
    public void testListFile() throws IOException {
//        File folder=new File("src\\io\\gitee\\xyuesheng");
        File folder = new File(".\\");

        long start = System.currentTimeMillis();//取当前时间的毫秒数

        //遍历文件树
        //Files,Paths（跟路径相关的工具类）
        Files.walkFileTree(Paths.get("src\\io\\gitee\\xyuesheng"), visitor);
//        Files.walkFileTree(Paths.get(".\\"),visitor);

        long end = System.currentTimeMillis();

        System.out.println("耗时" + (end - start));

    }


}
